import { Component, OnInit, Output, EventEmitter, Input, ViewChild, TemplateRef, HostBinding } from '@angular/core';
import { NotifyService } from '@farris/ui-notify';
import { DatagridComponent } from '@farris/ui-datagrid';
import { IdService } from '@farris/ui-common';
import { EditorTypes } from '@farris/ui-datagrid-editors';


@Component({
  selector: 'app-style-editor',
  templateUrl: './style-editor.component.html',
  styleUrls: ['./style-editor.component.css']
})
export class StyleEditorComponent implements OnInit {
  @Output() closeModal = new EventEmitter<any>();
  @Output() submitModal = new EventEmitter<any>();
  @Input() value: string;

  @HostBinding('class')
  class = 'd-flex f-utils-fill-flex-column h-100';

  @ViewChild('styleFooter') modalFooter: TemplateRef<any>;
  modalConfig = {
    title: '样式编辑器',
    width: 900,
    height: 500,
    showButtons: true
  };

  @ViewChild('dg') dg: DatagridComponent;
  columns = [
    { field: 'code', title: '样式编号', editor: { type: EditorTypes.TEXTBOX } },
    { field: 'value', title: '样式值', editor: { type: EditorTypes.TEXTBOX } }
  ];


  /**
   * 枚举弹框数据源
   * 用来保存过程中编辑数据
   */
  data = [];

  constructor(private notifyService: NotifyService, private idServ: IdService) { }

  ngOnInit() {
    if (!this.value) {
      this.data = [];
      return;
    }
    this.value.split(';').forEach(style => {
      const styleCode = style.split(':');
      if (styleCode.length === 2) {
        this.data.push({
          hId: this.idServ.generate(),
          code: styleCode[0].trim(),
          value: styleCode[1].trim()
        });
      }
    });
  }


  addItem() {
    // 触发单元格结束编辑
    this.dg.endEditing();

    this.dg.appendRow({
      hId: this.idServ.generate(),
      code: '',
      value: ''
    });
  }

  removeItem() {
    // 触发单元格结束编辑
    this.dg.endEditing();

    const row = this.dg.selectedRow;
    if (row) {
      this.dg.deleteRow(row.id);
      this.dg.clearSelections();
    } else {
      this.notifyService.warning('请选中要删除的行');
    }
  }

  clickCancel() {
    this.closeModal.emit();
  }

  clickConfirm() {
    // 触发单元格结束编辑
    this.dg.endEditing();


    // 获取最新数组
    const latestData = [];
    this.dg.data.forEach(d => {
      const { hId, ...other } = d;
      latestData.push(other);
    });


    if (latestData.length === 0) {
      this.submitModal.emit({ value: '' });
      return;
    }

    // 校验
    if (!this.checkBeforeSave(latestData)) {
      return;
    }



    const a = latestData.map(style => style.code.trim() + ':' + style.value.trim());
    this.value = a.join(';');

    this.submitModal.emit({ value: this.value });
  }

  /**
   * 保存前检查
   */
  checkBeforeSave(latestData: any[]): boolean {
    // ② 非空，则校验每个的键值是否为空；
    for (const item of latestData) {
      if (!item.code || !item.value) {
        this.notifyService.warning('样式编号和样式值均不允许为空。');
        return false;
      }
    }
    // ③ 键不允许重复；
    const enumKeys = latestData.map(e => e.code);
    const keySet = new Set(enumKeys);
    const exclusiveKeys = Array.from(keySet);
    if (enumKeys.length !== exclusiveKeys.length) {
      this.notifyService.warning('样式编号不允许重复。');
      return false;
    }
    return true;

  }
}
